﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "BTTaskNode/TaskGetRandomPosition.h"

#include "AIController.h"
#include "NavigationSystem.h"
#include "AI/NavigationSystemBase.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "Character/EnemyCharacter.h"

UTaskGetRandomPosition::UTaskGetRandomPosition()
{
	NodeName = FString("GetRandomPosition");
}

EBTNodeResult::Type UTaskGetRandomPosition::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
	// 获得aicontroller
	AAIController* AaiController = OwnerComp.GetAIOwner();

	// 获得blackboard
	UBlackboardComponent* BlackboardComponent = OwnerComp.GetBlackboardComponent();

	if (AaiController != nullptr && BlackboardComponent != nullptr)
	{
		// 获得aicontroller控制的敌人
		ABaseCharacter* BaseCharacter = Cast<ABaseCharacter>(AaiController->GetPawn());
		if (BaseCharacter)
		{
			FVector ActorLocation = BaseCharacter->GetActorLocation();
			// 导航工具
			UNavigationSystemV1* NavigationSystemV1 = FNavigationSystem::GetCurrent<UNavigationSystemV1>(this);
			if (NavigationSystemV1 != nullptr)
			{
				FNavLocation ResultLocation;
				// 获得随机地点
				bool IsFound = NavigationSystemV1->GetRandomReachablePointInRadius(
					ActorLocation, Radius, ResultLocation);
				if (IsFound)
				{
					// 设置blackboard变量
					BlackboardComponent->SetValueAsVector(MovePositionKey.SelectedKeyName, ResultLocation.Location);
					return EBTNodeResult::Succeeded;
				}
			}
		}
	}

	return EBTNodeResult::Failed;
}

uint16 UTaskGetRandomPosition::GetSpecialMemorySize() const
{
	return Super::GetSpecialMemorySize();
}
